class DirectMessageController < ApplicationController
  layout "settings"
  before_filter :authorize

  # To simplify the design of database, just ignore the delete function
  # If I add a delete function, I should have two databased to store
  # seperate copy of direct messages for senders and receivers or
  # add a new column to identify the status. That's not clean.

  def index
    @narrow_look = false
    @user = get_current_user(session[:user_name])
    @dm = DirectMessage.get_dm_by_id(@user.id)
    @dm_count = DirectMessage.get_dm_count_by_id(@user.id)
    @page_title = "#{@user.display_name}'s Direct Messages_Microblog"
    friend_id_list = Follower.get_friend_list(@user.id)
    @friend_list = []
    friend_id_list.each do |f|
      @friend_list << User.find(f.user_id)
    end
  end
  
  # this is the method deal with direct message save.
  
  def to
    @narrow_look = true
    user = get_current_user(session[:user_name])
    if !request.post? && params[:id].nil?
        redirect_to(:controller => :direct_message, :action => "index")
    else
      if !request.post?
        @user = User.find(params[:id])
        @page_title = "Direct Message to #{@user.display_name}_Microblog"
      else
        dm = DirectMessage.new
        dm.post_from = user.id
        dm.post_to = params[:id].nil? ? params[:user][:id].to_i : params[:id].to_i
        dm.post_at = Time.now
        text = text_process(params[:content])
        if text
          dm.content = text
          if dm.save
            flash[:notice] = "Direct message sent!"
          else
            flash[:notice] = "Failed to send direct message. :( "
          end
        else
          flash[:notice] = "You should send some 'real' text. :) "
        end
        redirect_to(:controller => :direct_message, :action => "index")
      end
    end
  end
  
  private
  
  def get_current_user(name)
    users = User.find(:all, :conditions => ["name='#{name}'"])
    users[0]
  end

  def text_process(text)
    text.strip!
    #get rid of all the special chars
    text.gsub!(/[\n\r\s\t]+/mu," ")
    if text == ""
      return false
    else
      # use jtext to solve the dirty problem.
      # I don't know if there is a slice method for
      # unicode.
      count = 0
      new_text = ''
      text.each_char do |mb|
        new_text += mb
        count += 1
        break if count >= 140
      end
      # add @ processing and url trim here.
      return new_text
    end
  end
  
end
